/*!
 @header OrderListViewController.m
 @author 王 文彬
 @version 1.0.0 2013/02/04 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "OrderListViewController.h"
#import "Config.h"
#import "Helper.h"
#import "OrderDetailViewController.h"
#import "DynamicDetailViewController.h"
#import "ConfirmPayViewController.h"
#import "JMFBase.h"
#import "ASImageView.h"
#import "RTLabel.h"
#import "HPopupView.h"
#import "MoonHTTPRequest.h"
#import "MJRefresh.h"

//取消订单 退款 退货 确认发货 确认收货 查看退款申请 查看退货申请
/*!
 @enum
 @abstract 此枚举用于区分当前用户在操作cell上的按钮所弹出来的actionsheet。
 UIAlertViewCancelOrderOption为取消订单；
 UIAlertViewRefundOption为退款；
 UIAlertViewReturnOption为退货。
 UIAlertViewDeliveryConfirmedOption为确认发货；
 UIAlertViewDeliveryTookOption为确认收货；
 UIAlertViewRefundApplicationOption为查看退款申请。
 UIAlertViewReturnApplicationOption为查看退货申请；
 
 @constant UIAlertViewCancelOrderOption 100
 @constant UIAlertViewRefundOption 101
 @constant UIAlertViewReturnOption 102
 @constant UIAlertViewDeliveryConfirmedOption 103
 @constant UIAlertViewDeliveryTookOption 104
 @constant UIAlertViewRefundApplicationOption 105
 @constant UIAlertViewReturnApplicationOption 106
 */
typedef enum{
    
    UIAlertViewCancelOrderOption=100,
    UIAlertViewRefundOption,
    UIAlertViewReturnOption,
    UIAlertViewDeliveryConfirmedOption,
    UIAlertViewDeliveryTookOption,
    UIAlertViewRefundApplicationOption,
    UIAlertViewReturnApplicationOption,
    UIAlertViewRefundCancelOption,
    UIAlertViewReturnCancelOption,
}UIAlertViewOption;

//  -----------------------类详细介绍-----------------------
//
//  <功能描述>：根据服务器返回来的订单类型判断订单类型。不同的订单类型有不同的时间逻辑、title和后续操作
//  一共6种订单，在订单详情中，各类订单的后续操作都不一样。
//  待付款订单显示购买时间，如果用户是买家则后续操作是去付款操作，如果用户是卖家时，则显示的是“等待买家付款”；
//  除此之外，如果用户是买家，cell上有“取消订单”的按钮功能。如果判断出此商品已下架，那么就要显示“此商品已下架”
//  当用户点击取消订单按钮后，会弹出一个alertview，提示用户是否继续此操作。点击“确定”则向服务器请求取消订单操作。

//  待发货订单显示付款时间，如果用户是买家则显示“等待卖家发货”，如果用户是卖家时，后续操作是确认发货操作；
//  除此之外，如果用户是买家，cell上有“申请退款”的按钮功能。
//  点击“申请退款”，会弹出一个自定义alertview，要用户填写1-99字的退款理由。点击“提交”则向服务器请求申请退款操作。

//  待收货订单显示发货时间，如果用户是买家则后续操作是待确认收货操作，如果用户是卖家时，则显示“等待买家确认”；
//  除此之外，如果用户是买家，cell上有“申请退货”的按钮功能。
//  点击“申请退货”，会弹出一个自定义alertview，要用户填写1-99字的退货理由。点击“提交”则向服务器请求申请退货操作。

//  历史成功订单显示收货时间，如果用户是买家且status=3则后续操作是去评论操作；如果用户是买家且则status=4则显示“已评论”；
//  如果用户是卖家且则status=5显示“已关闭”；如果用户是卖家且则status=4则显示“未评论”
//  点击“去评论”，会跳转到此订单的商品的动态详情VC。

//  待退款订单显示下单时间，如果用户是买家则显示“等待卖家退款”，如果用户是卖家时，后续操作是查看申请。
//  点击“查看申请”，会弹出一个自定义的alertview，提示用户是否要继续此操作；alertview上3个按钮，拒绝退款、确认退款和暂不处理；
//  
//
//  待退货订单显示下单时间，如果用户是买家则显示“等待卖家退款”，如果用户是卖家时，后续操作是查看申请。
//  点击“查看申请”，会弹出一个alertview，提示用户是否要继续此操作；alertview上3个按钮，拒绝退货、确认退货和暂不处理；
//
//  <功能描述>：此VC主要的地方为alertview的按钮操作，因为cell每一个row都会弹出至少一个alertview，通常可能会是两个，所以在alertview的代理方法中，
//          需要判断。是根据订单类型和alertview的tag判断
//       <实现描述>：如果退货和退款操作，点击的第3个按钮为“暂不处理”；
//             当为待发货订单时，alertview的tag为枚举变量UIAlertViewDeliveryConfirmedOption时，则确认时，是向服务器请求确认发货；
//             alertview的tag为枚举变量UIAlertViewRefundOption时，则确认时，是向服务器请求申请退款。以上逻辑同待收货订单。
//
//             当为待退款订单时，此alertview有3个按钮，当点击index=0的按钮时，则为拒绝退款；点击index=1，则为确认退款。以上逻辑同待退货订单。
//
//  -----------------------类升级日志-----------------------
//
//  修改人   修改时间        修改描述              版本
//
// <#修改人#> <#修改时间#>    <#修改描述#>          <#版本#>


@interface OrderListViewController ()<MJRefreshBaseViewDelegate>

@end

@implementation OrderListViewController
{
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
}
@synthesize orderListType = _orderListType;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithBusinessType:(BusinessType)businessType andOrderListType:(OrderListType)listType
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {
        _orderListType = listType;
        _businessType  = businessType;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _blankPage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 832.0f/2.0f)];
    
    //背景色
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    self.tableView.backgroundView = nil;
    
    //导航按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    switch (_orderListType) {
        case OrderListTypeWaitingForPay:
            
            self.title = _L(@"vc_title_022");
            break;
            
        case OrderListTypeWillDelivery:
            
            self.title = _L(@"vc_title_023");
            break;
        
        case OrderListTypeWaitingForConfirm:
            
            self.title = _L(@"vc_title_024");
            break;
        
        case OrderListTypeWaitingForComment:
            
            self.title = _L(@"vc_title_090");
            break;
            
        case OrderListTypeRefund:
            
            self.title = _L(@"vc_title_017");
            break;
            
        case OrderListTypeReturn:
            
            self.title = _L(@"vc_title_018");
            break;
        
        case OrderListTypeHistory:
            
            self.title = _L(@"vc_title_025");
            break;
    }

    _dataSource = [[NSMutableArray alloc] init];
    
    // 3.3行集成下拉刷新控件
    _header = [MJRefreshHeaderView header];
    _header.scrollView = self.tableView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.delegate = self;
    
    // 5.0.5秒后自动下拉刷新
//    [_header performSelector:@selector(beginRefreshing) withObject:nil afterDelay:0.5];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
//    [self refreshViewByCheckId:nil];
    [_header beginRefreshing];
}

#pragma mark - Table view data source

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [NSString stringWithFormat:@"%@ %@", [[_dataSource objectAtIndex:section] valueForKey:@"timePrefix"] ,[[_dataSource objectAtIndex:section] valueForKey:@"time"]];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%i", indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        if (indexPath.row == 0) {
            //头像
            ASImageView* imageView = [[ASImageView alloc] initWithFrame:CGRectMake(10, 5, 30, 30)];
            [cell.contentView addSubview:imageView];
            
            //用户名
            UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(45, 10, 100, 20)];
            label.font = _SYS_FONT_003;
            [cell.contentView addSubview:label];
            
            //配送方式
            RTLabel* methodLabel = [[RTLabel alloc] initWithFrame:CGRectMake(160, 15, 140, 20)];
            methodLabel.textAlignment = UITextAlignmentRight;
            methodLabel.textColor = _SYS_COLOR_002;
            methodLabel.font = _SYS_FONT_001;
            [cell.contentView addSubview:methodLabel];
        }
        
        else if (indexPath.row == 1) {
            //图片
            ASImageView* imageView = [[ASImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
            [cell.contentView addSubview:imageView];
            
            //产品名称
            UILabel* nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 3, 200, 20)];
            nameLabel.textColor = _SYS_COLOR_002;
            nameLabel.font = _SYS_FONT_004;
            [cell.contentView addSubview:nameLabel];
            
            //购买数量
            UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(70, 24, 220, 20)];
            label.font = _SYS_FONT_003;
            label.textColor = _SYS_COLOR_003;
            [cell.contentView addSubview:label];
            
            //总价
            RTLabel* amountLabel = [[RTLabel alloc] initWithFrame:CGRectMake(70, 46, 220, 20)];
            amountLabel.font = _SYS_FONT_003;
            amountLabel.textColor = _SYS_COLOR_003;
            [cell.contentView addSubview:amountLabel];
        }
        
        else if (indexPath.row == 2) {
            //状态文字，与确认按钮在同一个位置
            UILabel* statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 5, 80, 20)];
            statusLabel.font = _SYS_FONT_002;
            statusLabel.textColor = _SYS_COLOR_002;
            [cell.contentView addSubview:statusLabel];
            
            //确认按钮，与状态文字在同一个位置
            UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(210, 5, 80, 25)];
            button.titleLabel.font = _SYS_FONT_003;
            [button setBackgroundImage:[UIImage imageNamed:@"transaction_btn_002_n"] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:button];
            
            UIButton* button2 = [[UIButton alloc] initWithFrame:CGRectMake(5, 7, 70, 20)];
            button2.titleLabel.font = _SYS_FONT_002;
            [button2 setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
            [button2 addTarget:self action:@selector(button2Event:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:button2];

            UIButton* button3 = [[UIButton alloc] initWithFrame:CGRectMake(65, 7, 70, 20)];
            button3.titleLabel.font = _SYS_FONT_002;
            [button3 setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
            [button3 addTarget:self action:@selector(button3Event:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:button3];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    
    //订单表格第一行：买/卖家头像、名字，配送方式
    if (indexPath.row == 0) {
        //图片
        [((ASImageView *)[cell.contentView.subviews objectAtIndex:0]) setImageURL:[NSURL URLWithString:_dataSource[indexPath.section][@"avatar"]] andSourceImageURL:nil forStyle:PictureStyleAvartPreview];

        //名字
        ((UILabel *)[cell.contentView.subviews objectAtIndex:1]).text = _dataSource[indexPath.section][@"realname"];
        
        //配送方式
        NSString* methodString = [NSString stringWithFormat:_L(@"title_method_05"), [_dataSource[indexPath.section][@"deliveryMode"] integerValue] == 1 ? _L(@"title_method_03") : _L(@"title_method_02")];  //@"配送方式：%@" | @"快递" : @"自取"
        ((RTLabel *)[cell.contentView.subviews objectAtIndex:2]).text = methodString;
    }
    
    //订单表格第二行：图片，名称，购买数量，总价
    else if (indexPath.row == 1) {
        NSDictionary* product = _dataSource[indexPath.section][@"product"];
        //图片
        [((ASImageView *)[cell.contentView.subviews objectAtIndex:0]) setImageURL:[NSURL URLWithString:product[@"picturePreview"]] andSourceImageURL:nil forStyle:PictureStyleNormalPreview];
        
        //名称
        ((UILabel *)[cell.contentView.subviews objectAtIndex:1]).text = product[@"name"];
        
        //购买数量
        NSString* totalString = [NSString stringWithFormat:_L(@"tpl_39"), [_dataSource[indexPath.section][@"quantity"] integerValue], product[@"unitName"]];
        ((UILabel *)[cell.contentView.subviews objectAtIndex:2]).text = totalString;

        //总价
        NSString* amountString = [NSString stringWithFormat:_L(@"tpl_amount_01"), _dataSource[indexPath.section][@"amount"]];   //总价：<font color='#fd6c01'>%@</font>元
        ((UILabel *)[cell.contentView.subviews objectAtIndex:3]).text = amountString;
    }
    
    //订单表格第三行：cancel按钮、确认按钮、无确认按钮时的提示文字、提醒按钮
    else if (indexPath.row == 2) {
        
        //确认按钮的tag装入当前的行号
        ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).tag = indexPath.section;
        ((UIButton *)[cell.contentView.subviews objectAtIndex:2]).tag = indexPath.section;
        ((UIButton *)[cell.contentView.subviews objectAtIndex:3]).tag = indexPath.section;
        ((UIButton *)cell.contentView.subviews[2]).hidden = true;
        ((UIButton *)cell.contentView.subviews[3]).hidden = true;
        
        BOOL iAmSeller = !([_dataSource[indexPath.section][@"buyerID"] integerValue] == [_ACCOUNT_ID integerValue]);
        
        //历史订单，或未评论订单
        if (_orderListType == OrderListTypeHistory || _orderListType == OrderListTypeWaitingForComment) {

            //已评论
            if ([[[_dataSource objectAtIndex:indexPath.section] valueForKey:@"status"] integerValue] == 5) {
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = false;
                ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = true;
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).text = _L(@"title_01");   //已关闭
            }
            //已关闭
            else if ([[[_dataSource objectAtIndex:indexPath.section] valueForKey:@"status"] integerValue] == 4) {
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = false;
                ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = true;
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).text = _L(@"title_02");   //已评论
            }
        
            //否则就是带评论的未评论
            else {
                
                if (!iAmSeller) {
                    ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = true;
                    ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = false;
                    [((UIButton *)[cell.contentView.subviews objectAtIndex:1]) setTitle:_L(@"btn_confirm_04") forState:UIControlStateNormal];   //去评论
                }
                else {
                    ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).text = _L(@"title_03");   //未评论
                    ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = false;
                    ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = true;
                    
                    //我是卖家，能提醒评论
                    [((UIButton *)cell.contentView.subviews[2]) setTitle:_L(@"btn_confirm_13") forState:UIControlStateNormal]; //提醒评论
                    ((UIButton *)cell.contentView.subviews[2]).hidden = [self buttonShowTesting:_dataSource[indexPath.section]];
                }
            }
            
        }
        
        //等待付款
        else if (_orderListType == OrderListTypeWaitingForPay) {
            if (iAmSeller) {
                ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = true;
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = false;
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).text = _L(@"title_04");    //等待买家付款
                
                //我是卖家，能提醒付款
                [((UIButton *)cell.contentView.subviews[2]) setTitle:_L(@"btn_confirm_10") forState:UIControlStateNormal]; //提醒付款
                ((UIButton *)cell.contentView.subviews[2]).hidden = [self buttonShowTesting:_dataSource[indexPath.section]];
            }
            
            else {
                ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = false;
                [((UIButton *)[cell.contentView.subviews objectAtIndex:1]) setTitle:_L(@"btn_confirm_09") forState:UIControlStateNormal];    //去付款
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = true;
                
                //我是买家，可以取消订单
                [((UIButton *)cell.contentView.subviews[2]) setTitle:_L(@"btn_confirm_06") forState:UIControlStateNormal]; //取消订单
                ((UIButton *)cell.contentView.subviews[2]).hidden = false;
            }
            
            //商品下架
            if ([[_dataSource objectAtIndex:indexPath.section][@"productStatus"] intValue] != 0) {
                
                ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = true;
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = false;
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).text = _L(@"alert_09");   //该商品已下架
            }
        }
        
        //待发货
        else if (_orderListType == OrderListTypeWillDelivery) {
            if (iAmSeller) {
                ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = false;
                [((UIButton *)[cell.contentView.subviews objectAtIndex:1]) setTitle:_L(@"btn_confirm_02") forState:UIControlStateNormal];   //确认发货
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = true;

                //我是卖家，没有多余行为
            }
            
            else {
                ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = true;
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = false;
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).text = _L(@"title_05");    //等待卖家发货
                
                //我是买家，可以申请退款
                [((UIButton *)cell.contentView.subviews[2]) setTitle:_L(@"btn_confirm_07") forState:UIControlStateNormal]; //提醒发货
                ((UIButton *)cell.contentView.subviews[2]).hidden = false;
                
                //也可以提醒卖家发货
                [((UIButton *)cell.contentView.subviews[3]) setTitle:_L(@"btn_confirm_11") forState:UIControlStateNormal]; //提醒发货
                ((UIButton *)cell.contentView.subviews[3]).hidden = [self buttonShowTesting:_dataSource[indexPath.section]];
            }
        }
        
        //待收货
        else if (_orderListType == OrderListTypeWaitingForConfirm) {
            if (iAmSeller) {
                ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = true;
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = false;
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).text = _L(@"title_06");   //等待买家确认
               
                //我是卖家，可以提醒收货
                [((UIButton *)cell.contentView.subviews[2]) setTitle:_L(@"btn_confirm_12") forState:UIControlStateNormal]; //提醒收货
                ((UIButton *)cell.contentView.subviews[2]).hidden = [self buttonShowTesting:_dataSource[indexPath.section]];
            }
            
            else {
                ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = false;
                [((UIButton *)[cell.contentView.subviews objectAtIndex:1]) setTitle:_L(@"btn_confirm_03") forState:UIControlStateNormal];   //确认收货
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = true;
                
                //我是买家，可以申请退货
                [((UIButton *)cell.contentView.subviews[2]) setTitle:_L(@"btn_confirm_08") forState:UIControlStateNormal]; //申请退货
                ((UIButton *)cell.contentView.subviews[2]).hidden = false;
            }
        }
        //待退款
        else if (_orderListType == OrderListTypeRefund) {
            if (iAmSeller) {
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = true;
                ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = false;
                [((UIButton *)[cell.contentView.subviews objectAtIndex:1]) setTitle:_L(@"btn_confirm_05") forState:UIControlStateNormal];   //查看申请
                ((UIButton *)[cell.contentView.subviews objectAtIndex:2]).hidden = true;
            }
            
            else {
                ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = true;
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).text = _L(@"title_07");   //等待卖家退款
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = false;
                
                ((UIButton *)[cell.contentView.subviews objectAtIndex:2]).hidden = false;
                [((UIButton *)[cell.contentView.subviews objectAtIndex:2]) setTitle:_L(@"btn_yes_33") forState:UIControlStateNormal];
            }
        }
        //待退货
        else if (_orderListType == OrderListTypeReturn) {
            if (iAmSeller) {
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = true;
                ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = false;
                [((UIButton *)[cell.contentView.subviews objectAtIndex:1]) setTitle:_L(@"btn_confirm_05") forState:UIControlStateNormal];   //查看申请
                ((UIButton *)[cell.contentView.subviews objectAtIndex:2]).hidden = true;
            }
            
            else {
                ((UIButton *)[cell.contentView.subviews objectAtIndex:1]).hidden = true;
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).text = _L(@"title_08");   //等待卖家退货
                ((UILabel *)[cell.contentView.subviews objectAtIndex:0]).hidden = false;
                
                ((UIButton *)[cell.contentView.subviews objectAtIndex:2]).hidden = false;
                [((UIButton *)[cell.contentView.subviews objectAtIndex:2]) setTitle:_L(@"btn_yes_34") forState:UIControlStateNormal];
            }
        }
        
    }
    
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    
    
    //-    OrderDetailViewController* orderDetailViewController = [[OrderDetailViewController alloc] init];
    //-    orderDetailViewController.order = [_dataSource objectAtIndex:indexPath.section];
    NSInteger orderID = [[_dataSource objectAtIndex:indexPath.section][@"id"] integerValue];
    OrderDetailViewController* orderDetailViewController = [[OrderDetailViewController alloc] initWithOrderID:orderID];
    orderDetailViewController.dismissModal = true;
    
    UINavigationController* orderDetailNavigationController = [[UINavigationController alloc] initWithRootViewController:orderDetailViewController];
 
    [Helper navigationControllerCommonStyle:orderDetailNavigationController];
    
    [self.navigationController presentModalViewController:orderDetailNavigationController animated:true];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height = 0;
    
    if (indexPath.row == 0) {
        height = 40;
    }
    else if (indexPath.row == 1) {
        height = 70;
    }
    else if (indexPath.row == 2) {
        height = 35;
    }
    
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

- (void)makeOrderListDataSource:(NSDictionary *)data
{
    NSArray* values = [data valueForKey:@"data"];
    
    for (NSDictionary* order in values) {
        NSMutableDictionary* cell = [[NSMutableDictionary alloc] init];
        
        [cell setValue:[NSString stringWithFormat:@"%ld", [order[@"id"] longValue]] forKey:@"id"];
        [cell setValue:[NSString stringWithFormat:@"%.2f", [order[@"totalAmount"] floatValue]] forKey:@"amount"];
        [cell setValue:order[@"deliveryMode"]     forKey:@"deliveryMode"];
        [cell setValue:order[@"dynamicId"]        forKey:@"dynamicID"];
        [cell setValue:order[@"orderNumber"]      forKey:@"orderNumber"];
        [cell setValue:order[@"id"]               forKey:@"orderId"];
        [cell setValue:order[@"buyerId"]          forKey:@"buyerID"];
        [cell setValue:order[@"returnReason"]     forKey:@"returnReason"];
        [cell setValue:order[@"refundReason"]     forKey:@"refundReason"];
        [cell setValue:order[@"quantity"]         forKey:@"quantity"];
        [cell setValue:order[@"status"]           forKey:@"status"];
        
        switch (_orderListType) {
            case OrderListTypeWillDelivery:
                [cell setValue:order[@"paymentTime"] forKey:@"time"];
                [cell setValue:@"付款时间：" forKey:@"timePrefix"];
                break;
                
            case OrderListTypeWaitingForPay:
                [cell setValue:order[@"createTime"] forKey:@"time"];
                [cell setValue:@"购买时间：" forKey:@"timePrefix"];
                break;
                
            case OrderListTypeWaitingForConfirm:
                [cell setValue:order[@"deliveryTime"] forKey:@"time"];
                [cell setValue:@"发货时间：" forKey:@"timePrefix"];
                break;
                
            case OrderListTypeHistory:
                [cell setValue:order[@"receiveTime"] forKey:@"time"];
                [cell setValue:@"收货时间：" forKey:@"timePrefix"];
                break;
                
            case OrderListTypeRefund:
                [cell setValue:order[@"createTime"] forKey:@"time"];
                [cell setValue:@"下单时间：" forKey:@"timePrefix"];
                break;
                
            case OrderListTypeReturn:
                [cell setValue:order[@"createTime"] forKey:@"time"];
                [cell setValue:@"下单时间：" forKey:@"timePrefix"];
                break;
                
            case OrderListTypeWaitingForComment:
                [cell setValue:order[@"receiveTime"] forKey:@"time"];
                [cell setValue:@"收货时间：" forKey:@"timePrefix"];
        }
        
        [cell setValue:order[@"product"] forKey:@"product"];
        
        BOOL iAmSeller = !([cell[@"buyerID"] integerValue] == [_ACCOUNT_ID integerValue]);
        
        if (iAmSeller) {
            [cell setValue:order[@"buyerAvatar"] forKey:@"avatar"];
            [cell setValue:order[@"buyerRealName"] forKey:@"realname"];
        }
        else {
            [cell setValue:order[@"sellerAvatar"] forKey:@"avatar"];
            [cell setValue:order[@"sellerRealName"] forKey:@"realname"];
        }
        
        [_dataSource addObject:cell];
    }
}
#pragma mark - JSONDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if (_dataSource.count != 0) {
            
            [_dataSource removeAllObjects];
        }
        
        //将每次下拉刷新出的新数据都加入到数据源的最前面
        if ([(NSArray *)jmf.data count] != 0) {
            
            [self makeOrderListDataSource:dict];
            
            _footer.scrollView = self.tableView;
        }
        
        if (_dataSource.count > 0) {
            self.tableView.tableFooterView.hidden = NO;
        }
        else {
            self.tableView.tableFooterView.hidden = YES;
        }
        
        [self reloadTableView];
        
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
    
    //页面为空时的友好设置
    if (_dataSource.count == 0) {
        
        _blankPage.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_004@2x" ofType:@"png"]];
        self.view.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_blankPage];
        
    }else{
        
        self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
        [_blankPage removeFromSuperview];
    }
}

- (void)moreOrdersDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if ([(NSArray *)jmf.data count] != 0) {
            self.tableView.tableFooterView.hidden = NO;
            [self makeOrderListDataSource:dict];

        }
        else{
            self.tableView.tableFooterView.hidden = YES;
        }
        [self reloadTableView];
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}


//
- (void)requestSuccessSelector:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        [self refreshViewByCheckId:nil];
        
        //如果前面定义了成功字符串，就显示，显示后销毁字串，以免下次按钮点击后，没有赋值时，误弹出
        if (_successTitle != nil) {
            [Helper showAllTextDialog:_successTitle inView:nil];
            _successTitle = nil;
        }
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}


#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent
{
    [self.navigationController popViewControllerAnimated:true];
}

/*!
 @abstract 取消按钮事件
 */
- (void)button2Event:(id)sender
{
    _remindButton = sender;
    _currentRow = ((UIButton *)sender).tag;
    //    NSDictionary* order = [_dataSource objectAtIndex:_currentRow];

    _reasonTextView = [[UITextView alloc] initWithFrame: CGRectMake(12.0, 70.0, 240.0, 80.0)];
    _reasonTextView.font = [UIFont boldSystemFontOfSize:15];
    _reasonTextView.layer.cornerRadius = 6;
    _reasonTextView.layer.masksToBounds = YES;
    _reasonTextView.layer.borderColor = [[UIColor grayColor] CGColor];
    _reasonTextView.layer.borderWidth = 1;
    
    BOOL iAmSeller = !([_dataSource[_currentRow][@"buyerID"] integerValue] == [_ACCOUNT_ID integerValue]);
    NSString* orderId = _dataSource[_currentRow][@"id"];
    
    //待付款，如果是买家，就是取消订单
    if (_orderListType == OrderListTypeWaitingForPay && !iAmSeller) {
        
        UIAlertView* alertForCancel = [[UIAlertView alloc] initWithTitle:_L(@"alert_16") message:nil delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];   //确定要取消当前订单吗？
        alertForCancel.tag = UIAlertViewCancelOrderOption;
        [alertForCancel show];
    }
    //待付款，如果是卖家，就是提醒付款
    else if (_orderListType == OrderListTypeWaitingForPay && iAmSeller) {

        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ORDER_REMIND_PAY];
        request.hudOn = true;
        request.delegate = self;
        request.successSelector = @selector(requestRemindSuccess:);
        [request setValue:orderId forParameter:@"productOrderId"];
        [request asynchronous];
    }
    //待发货，如果是卖家，没有这个事件
    else if (_orderListType == OrderListTypeWillDelivery && iAmSeller) {
    }
    //待发货，如果是买家，就是申请退款
    else if (_orderListType == OrderListTypeWillDelivery && !iAmSeller) {
        
        HPopupView* popupView = [[HPopupView alloc] initWithFrame:CGRectMake(30, 40, 260, 200)];
        popupView.cancelButtonTitle = _L(@"btn_no_01");
        [popupView addButtonTitlt:_L(@"btn_yes_01")];
        popupView.titleText = _L(@"alert_17");
        popupView.contentText = _L(@"alert_19");
        
        [popupView setWillShowBlock:^(UIView *view) {
            
            [view addSubview:_reasonTextView];
            [_reasonTextView becomeFirstResponder];
        }];
        
        [popupView show];
        
        [popupView setButtonClickedBlock:^BOOL(UIView *view, NSInteger buttonIndex) {
            
            if (buttonIndex == 0) {
                
                return true;
            }
            
            JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ORDER_REFUND_APPLY];
            request.delegate = self;
            request.hudOn = true;
            request.hudTitle = _L(@"title_loading_01");
            [request setSuccessSelector:@selector(requestSuccessSelector:)];
            [request setValue:[_dataSource objectAtIndex:_currentRow][@"id"] forParameter:@"productOrderId"];
            [request setValue:_reasonTextView.text forParameter:@"refundReason"];
            [request asynchronous];
                    
            return true;
        }];
    }
    //待确认，如果是卖家，就是提醒收货
    else if (_orderListType == OrderListTypeWaitingForConfirm && iAmSeller) {
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ORDER_REMIND_RECEIVING];
        request.hudOn = true;
        request.delegate = self;
        request.successSelector = @selector(requestRemindSuccess:);
        [request setValue:orderId forParameter:@"productOrderId"];
        [request asynchronous];
    }
    //待确认，如果是买家，就是申请退货
    else if (_orderListType == OrderListTypeWaitingForConfirm) {
        
//        UIAlertView *alertForCancel = [[UIAlertView alloc] initWithTitle: _L(@"alert_128")
//                                                                 message: _L(@"alert_19")
//                                                                delegate: self
//                                                       cancelButtonTitle: _L(@"btn_no_01")
//                                                       otherButtonTitles: _L(@"btn_yes_05"),nil];
//        
//        [alertForCancel setTransform: CGAffineTransformMakeTranslation(0.0, -100)];
//        [alertForCancel addSubview: _reasonTextView];
//        alertForCancel.tag = UIAlertViewReturnOption;
//        [alertForCancel show];
        
        HPopupView* popupView = [[HPopupView alloc] initWithFrame:CGRectMake(30, 40, 260, 200)];
        popupView.cancelButtonTitle = _L(@"btn_no_01");
        [popupView addButtonTitlt:_L(@"btn_yes_01")];
        popupView.titleText = _L(@"alert_128");
        popupView.contentText = _L(@"alert_19");
        
        [popupView setWillShowBlock:^(UIView *view) {
            
            [view addSubview:_reasonTextView];
            [_reasonTextView becomeFirstResponder];
        }];
        
        [popupView show];
        
        [popupView setButtonClickedBlock:^BOOL(UIView *view, NSInteger buttonIndex) {
            
            if (buttonIndex == 0) {
                
                return true;
            }

            JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ORDER_RETURN_APPLY];
            request.delegate = self;
            request.hudOn = true;
            request.hudTitle = _L(@"title_loading_01");
            [request setSuccessSelector:@selector(requestSuccessSelector:)];
            [request setValue:[_dataSource objectAtIndex:_currentRow][@"id"] forParameter:@"productOrderId"];
            [request setValue:_reasonTextView.text forParameter:@"returnReason"];
            [request asynchronous];
            
            return true;
        }];
    }
    //待评论订单，如果是卖家，就是提醒评论
    else if ((_orderListType == OrderListTypeWaitingForComment || _orderListType == OrderListTypeHistory) && iAmSeller) {
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ORDER_REMIND_COMMENT];
        request.hudOn = true;
        request.delegate = self;
        request.successSelector = @selector(requestRemindSuccess:);
        [request setValue:orderId forParameter:@"productOrderId"];
        [request asynchronous];
    }
    //待退款，如果是买家，就执行
    else if (_orderListType == OrderListTypeRefund && !iAmSeller) {
        
        UIAlertView *alertForCancel = [[UIAlertView alloc] initWithTitle: _L(@"alert_102")
                                                                 message: nil
                                                                delegate: self
                                                       cancelButtonTitle: _L(@"btn_no_01")
                                                       otherButtonTitles: _L(@"btn_yes_05"),nil];
        
        alertForCancel.tag = UIAlertViewRefundCancelOption;
        [alertForCancel show];        
    }
    //待退货，如果是买家，就执行
    else if (_orderListType == OrderListTypeReturn && !iAmSeller) {
        
        UIAlertView *alertForCancel = [[UIAlertView alloc] initWithTitle: _L(@"alert_103")
                                                                 message: nil
                                                                delegate: self
                                                       cancelButtonTitle: _L(@"btn_no_01")
                                                       otherButtonTitles: _L(@"btn_yes_05"),nil];

        alertForCancel.tag = UIAlertViewReturnCancelOption;
        [alertForCancel show];
    }
}

/*!
 @abstract cell中的各种确认事件，如发货、付款等操作
 */
- (void)button3Event:(id)sender {
    
    _remindButton = sender;
    _currentRow = ((UIButton *)sender).tag;
    BOOL iAmSeller = !([_dataSource[_currentRow][@"buyerID"] integerValue] == [_ACCOUNT_ID integerValue]);

    //待付款，如果是买家，就是提醒发货
    if (_orderListType == OrderListTypeWillDelivery && !iAmSeller) {
        
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ORDER_REMIND_DELIVERY];
        request.hudOn = true;
        request.delegate = self;
        request.successSelector = @selector(requestRemindSuccess:);
        [request setValue:_dataSource[_currentRow][@"id"] forParameter:@"productOrderId"];
        [request asynchronous];
    }
}

/*!
 @abstract 各种提醒的请求成功句柄
 */
- (void)requestRemindSuccess:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    if (jmf.status == JMStatusSucceed) {
        
        //发送提醒成功后，隐藏提醒按钮
        _remindButton.hidden = true;
        //并记录那一行数据被隐藏，记录数据中的id，避免重新加载数据后错位计算
        if (!_remindButtonHiddenRecords) {
            
            _remindButtonHiddenRecords = [[NSMutableArray alloc] init];
        }
        [_remindButtonHiddenRecords addObject:_dataSource[_currentRow][@"id"]];
        
        [Helper showAllTextDialog:jmf.message inView:nil];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

/*!
 @abstract 退款和退货
 */
- (void)requestReturnOrRefundSuccess:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    if (jmf.status == JMStatusSucceed) {
        
        [_dataSource removeObjectAtIndex:_currentRow];
        [self.tableView reloadData];
        
        [Helper showAllTextDialog:jmf.message inView:nil];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

/*!
 @abstract cell中的各种确认事件，如发货、付款等操作
 */
- (void)buttonEvent:(id)sender
{
    _currentRow = ((UIButton *)sender).tag;
    _currentOperateOrder = [_dataSource objectAtIndex:_currentRow];   //1.7.7启用的变量，用于记录当前操作的订单号。为避免确认收货后，去评论时，_currentRow取数据错误的取到尚在本页内未收货的订单数据

    //快递上门
    if (_orderListType == OrderListTypeWillDelivery && [_dataSource[_currentRow][@"deliveryMode"] intValue] == 1) {
    
        UITextField* companyTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, 95, 230, 25)];
        companyTextField.placeholder = _L(@"holder_32");
        companyTextField.font = [UIFont boldSystemFontOfSize:15];
        companyTextField.layer.cornerRadius = 4;
        companyTextField.layer.masksToBounds = YES;
        companyTextField.backgroundColor = UIColor.whiteColor;
        companyTextField.text = _company;
        companyTextField.tag = 100;
        companyTextField.delegate = (id)self;
        companyTextField.borderStyle = UITextBorderStyleRoundedRect;
        [companyTextField becomeFirstResponder];
        
        UITextField* noTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, 127, 230, 25)];
        noTextField.placeholder = _L(@"holder_33");
        noTextField.font = [UIFont boldSystemFontOfSize:15];
        noTextField.layer.cornerRadius = 6;
        noTextField.layer.masksToBounds = YES;
        noTextField.backgroundColor = UIColor.whiteColor;
        noTextField.text = _no;
        noTextField.tag = 101;
        noTextField.delegate = (id)self;
        noTextField.borderStyle = UITextBorderStyleRoundedRect;
        
        HPopupView* popupView = [[HPopupView alloc] initWithFrame:CGRectMake(30, 40, 260, 200)];
        popupView.cancelButtonTitle = _L(@"btn_no_01");
        [popupView addButtonTitlt:_L(@"btn_yes_01")];
        popupView.titleText = _L(@"title_79");
        popupView.contentText = _L(@"alert_76");
        
        [popupView setWillShowBlock:^(UIView *view) {
            
            [view addSubview:companyTextField];
            [view addSubview:noTextField];
        }];
        
        [popupView show];
        
        [popupView setButtonClickedBlock:^BOOL(UIView *view, NSInteger buttonIndex) {
            
            if (buttonIndex == 0) {
                
                return true;
            }
            
            _no = noTextField.text;
            _company = companyTextField.text;
            
            NSString* alert;
            if (_no.length > 0) {
                if (_no.length < 2) {
                    alert = _L(@"alert_81");
                }
                else if (_no.length > 50) {
                    alert = _L(@"alert_82");
                }
            }
            if (_company.length > 0 && _no.length == 0) {
                alert = _L(@"alert_78");
            }
            
            if (_company.length > 0) {
                if (_company.length < 2) {
                    alert = _L(@"alert_79");
                }
                else if (_company.length > 50) {
                    alert = _L(@"alert_80");
                }
            }
            if (_company.length == 0 && _no.length > 0) {
                alert = _L(@"alert_77");
            }
            
            if (alert) {
                
                [Helper showAlertWithTitle:nil andMessage:alert];
                return false;
            }
            
            JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ORDER_CONDIGNMENT];
            request.delegate = self;
            request.hudOn = true;
            request.hudTitle = _L(@"title_loading_01");
            [request setSuccessSelector:@selector(requestSuccessSelector:)];
            [request setValue:[_dataSource objectAtIndex:_currentRow][@"id"] forParameter:@"productOrderId"];
            [request setValue:_company forParameter:@"logisticsCompany"];
            [request setValue:_no forParameter:@"logisticsNumber"];
            [request asynchronous];
            
            _company = @"";
            _no = @"";
            
            return true;
        }];
    }
    else if (_orderListType == OrderListTypeWillDelivery) {
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_06") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_05"), nil];
        alertView.tag = UIAlertViewDeliveryConfirmedOption;
        [alertView show];
    }
    else if (_orderListType == OrderListTypeWaitingForConfirm) {
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_07") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_05"), nil];
        alertView.tag = UIAlertViewDeliveryTookOption;
        [alertView show];
    }
    else if (_orderListType == OrderListTypeWaitingForComment || _orderListType == OrderListTypeHistory) {

        DynamicDetailViewController* dynamicDetailViewController = [[DynamicDetailViewController alloc] initWithID:[[[_dataSource objectAtIndex:_currentRow] valueForKey:@"dynamicID"] intValue]];
        dynamicDetailViewController.disMode = true;
        dynamicDetailViewController.orderId = [_dataSource[_currentRow][@"orderId"] intValue];

        UINavigationController* messageFormNavigationController = [[UINavigationController alloc] initWithRootViewController:dynamicDetailViewController];

        [Helper navigationControllerCommonStyle:messageFormNavigationController];
        
        
        [self.navigationController presentModalViewController:messageFormNavigationController animated:true];
    }
    else if(_orderListType == OrderListTypeWaitingForPay) {
        
        ConfirmPayViewController* payViewController = [[ConfirmPayViewController alloc] initWithOrder:_dataSource[_currentRow]];
        payViewController.dismissModal = true;
        
        UINavigationController* messageFormNavigationController = [[UINavigationController alloc] initWithRootViewController:payViewController];

        [Helper navigationControllerCommonStyle:messageFormNavigationController];
        [self.navigationController presentModalViewController:messageFormNavigationController animated:true];
    }
    else if (_orderListType == OrderListTypeRefund) {
        
        NSString *reason = nil;
        
        if([_dataSource objectAtIndex:_currentRow][@"refundReason"] == nil || [@"" isEqualToString:[_dataSource objectAtIndex:_currentRow][@"refundReason"]]){
            
            reason = _L(@"title_09");    //@"退款理由：%@", @"无"
        }else{
            
            reason = [_dataSource objectAtIndex:_currentRow][@"refundReason"];
        }

        HPopupView* popupView = [[HPopupView alloc] init];
        popupView.titleText = [NSString stringWithFormat:_L(@"title_refund_01"), @""];
        popupView.contentText = reason;
        popupView.cancelButtonTitle = _L(@"btn_refund_03");
        [popupView addButtonTitlt:_L(@"btn_refund_01")];
        [popupView addButtonTitlt:_L(@"btn_refund_02")];
        [popupView show];
        [popupView setButtonClickedBlock:^BOOL(UIView *view, NSInteger buttonIndex) {
            
            if (buttonIndex == 0) {
                return true;
            }
            
            JSONRequest* request = [[JSONRequest alloc] init];
            request.delegate = self;
            request.hudOn = true;
            request.hudTitle = _L(@"title_loading_01");
            [request setSuccessSelector:@selector(requestSuccessSelector:)];
            [request setValue:[_dataSource objectAtIndex:_currentRow][@"id"] forParameter:@"productOrderId"];
            
            if (buttonIndex == 1) {
                
                request.URLString = _JSON_URL_ORDER_REFUND_CANCEL;
            }
            else if (buttonIndex == 2) {
                
                request.URLString = _JSON_URL_ORDER_REFUND_CONFIRM;
            }
            [request asynchronous];
            
            return true;
        }];

    }
    else if (_orderListType == OrderListTypeReturn) {
        
        NSString *reason = nil;
        
        if([_dataSource objectAtIndex:_currentRow][@"returnReason"] == nil || [@"" isEqualToString:[_dataSource objectAtIndex:_currentRow][@"returnReason"]]){
            
            reason = _L(@"title_09");   //@"退货理由：%@", @"无"
        }else{
            
            reason = [_dataSource objectAtIndex:_currentRow][@"returnReason"];
        }
        
        
        HPopupView* popupView = [[HPopupView alloc] init];
        popupView.titleText = [NSString stringWithFormat:_L(@"title_return_01"), @""];
        popupView.contentText = reason;
        popupView.cancelButtonTitle = _L(@"btn_return_03");
        [popupView addButtonTitlt:_L(@"btn_return_01")];
        [popupView addButtonTitlt:_L(@"btn_return_02")];
        [popupView show];
        [popupView setButtonClickedBlock:^BOOL(UIView *view, NSInteger buttonIndex) {
            
            if (buttonIndex == 0) {
                return true;
            }
            
            JSONRequest* request = [[JSONRequest alloc] init];
            request.delegate = self;
            request.hudOn = true;
            request.hudTitle = _L(@"title_loading_01");
            [request setSuccessSelector:@selector(requestSuccessSelector:)];
            [request setValue:[_dataSource objectAtIndex:_currentRow][@"id"] forParameter:@"productOrderId"];
            
            if (buttonIndex == 1) {
                
                request.URLString = _JSON_URL_ORDER_RETURN_CANCEL;
            }
            else if (buttonIndex == 2) {
                
                request.URLString = _JSON_URL_ORDER_RETURN_CONFIRM;
            }
            [request asynchronous];
            
            return true;
        }];
    }
    
}

#pragma mark - UIAlertView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    //如果退货和退款，点击的第3个按钮
    if (((_orderListType == OrderListTypeRefund || _orderListType == OrderListTypeReturn) && buttonIndex == 2 ) ||
        //或不是退款和退货，点击的第一个按钮
        (_orderListType != OrderListTypeRefund && _orderListType != OrderListTypeReturn && buttonIndex == 0 )) {
        
        return;
    }
    
    //确认收货后的询问是否去评论的alertview，且点击了去评论按钮
    if (alertView.tag == 901 && buttonIndex == 1) {
        
        DynamicDetailViewController* dynamicDetailViewController = [[DynamicDetailViewController alloc] initWithID:[_currentOperateOrder[@"dynamicID"] integerValue]];
        dynamicDetailViewController.disMode = true;
        dynamicDetailViewController.orderId = [_currentOperateOrder[@"id"] integerValue];
        
        UINavigationController* messageFormNavigationController = [[UINavigationController alloc] initWithRootViewController:dynamicDetailViewController];
        [Helper navigationControllerCommonStyle:messageFormNavigationController];
        
        [self.navigationController presentModalViewController:messageFormNavigationController animated:true];
        
        return;
    }
    
    JSONRequest* request = [[JSONRequest alloc] init];
    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    [request setSuccessSelector:@selector(requestSuccessSelector:)];
    [request setValue:[_dataSource objectAtIndex:_currentRow][@"id"] forParameter:@"productOrderId"];
    
    
    if (_orderListType == OrderListTypeWillDelivery) {
        
        if (alertView.tag == UIAlertViewDeliveryConfirmedOption) {
            
            request.URLString = _JSON_URL_ORDER_CONDIGNMENT;
        }
//申请退款
//        else if(alertView.tag == UIAlertViewRefundOption){
//            
//            request.URLString = _JSON_URL_ORDER_REFUND_APPLY;
//            [request setValue:_reasonTextView.text forParameter:@"refundReason"];
//            _successTitle = _L(@"alert_71");
//        }
    }
    else if (_orderListType == OrderListTypeWaitingForConfirm) {
        
        if (alertView.tag == UIAlertViewDeliveryTookOption) {
            
//            request.URLString = _JSON_URL_ORDER_RECEIPT;
            MoonHTTPRequest* moon = [[MoonHTTPRequest alloc] initWithURLString:_JSON_URL_ORDER_RECEIPT];
            moon.progressOn = true;
            moon.progressTitle = _L(@"title_loading_01");
            [moon setParameter:[_dataSource objectAtIndex:_currentRow][@"id"] forName:@"productOrderId"];
            [moon onSuccess:^(id result) {
                
                JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:result];
                
                if (jmf.status == JMStatusSucceed) {
                    
                    [self refreshViewByCheckId:nil];
                    
                    //如果前面定义了成功字符串，就显示，显示后销毁字串，以免下次按钮点击后，没有赋值时，误弹出
                    if (_successTitle != nil) {
                        [Helper showAllTextDialog:_successTitle inView:nil];
                        _successTitle = nil;
                    }
                    
                    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_139") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_confirm_04"), nil];
                    alertView.tag = 901;
                    [alertView show];
                }
                else {
                    
                    [Helper easyShowJMFStatus:jmf];
                }
                
            } onFailure:^(NSError *error) {
                [self requestFailWithNetworkUnavailabe];
            }];
            [moon asynchronous];
            
            return;  //使用了moon，立即返回，否则后面的jsonrequest调用会异常
        }
//申请退货
//        else if(alertView.tag == UIAlertViewReturnOption){
//            
//            request.URLString = _JSON_URL_ORDER_RETURN_APPLY;
//            [request setValue:_reasonTextView.text forParameter:@"returnReason"];
//        }
    }
    else if (_orderListType == OrderListTypeRefund) {
        
        if (alertView.tag == UIAlertViewRefundCancelOption) {
            
            if (buttonIndex == 1) {
                request.URLString = _JSON_URL_ORDER_REFUND_APPLY_CANCEL;
                request.successSelector = @selector(requestReturnOrRefundSuccess:);
            }
            else {
                return;
            }
        }
//        else {
//            if (buttonIndex == 0) {
//                
//                request.URLString = _JSON_URL_ORDER_REFUND_CANCEL;
//            }
//            else if (buttonIndex == 1) {
//                
//                request.URLString = _JSON_URL_ORDER_REFUND_CONFIRM;
//            }
//        }
    }
    else if (_orderListType == OrderListTypeReturn) {
        
        if (alertView.tag == UIAlertViewReturnCancelOption) {
            
            if (buttonIndex == 1) {
                request.URLString = _JSON_URL_ORDER_RETURN_APPLY_CANCEL;
                request.successSelector = @selector(requestReturnOrRefundSuccess:);
            }
            else {
                return;
            }
        }
//        else {
//            if (buttonIndex == 0) {
//                
//                request.URLString = _JSON_URL_ORDER_RETURN_CANCEL;
//            }
//            else if (buttonIndex == 1) {
//                
//                request.URLString = _JSON_URL_ORDER_RETURN_CONFIRM;
//            }
//        }
    }
    else if (_orderListType == OrderListTypeWaitingForPay) {
        
        request.URLString = _JSON_URL_ORDER_CANCEL;
    }
    
    [request asynchronous];
}


#pragma mark - 私有方法

/*!
 @abstract 通过checkid查询向服务器请求订单记录
 @param checkId 需要分页功能时，传入此id，即数据源中最后一条数据的ID
 */
- (void)refreshViewByCheckId:(NSString *)checkId
{
    NSString* urlString = _businessType == BusinessTypeSeller ? _JSON_URL_ORDER_SELLER_LIST : _JSON_URL_ORDER_BUYER_LIST;
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:urlString];
    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_02");
    [request setValue:@(_orderListType) forParameter:@"status"];
    
    //id不为空，说明用户在加载更多
    if(checkId != nil){
        
        [request setValue:checkId forParameter:@"checkId"];
        
        [request setSuccessSelector:@selector(moreOrdersDidReceived:)];
    }
    
    [request asynchronous];
}

/*!
 @abstract 设定VC显示的订单列表类型
 */
- (void)setOrderListType:(OrderListType)orderListType
{
    _orderListType = orderListType;
    
    self.title = @[_L(@"vc_title_022"), _L(@"vc_title_023"), _L(@"vc_title_024"), _L(@"vc_title_025"), _L(@"vc_title_026"), _L(@"vc_title_027")][orderListType];
}

/*!
 @abstract 获取数据源最后一条数据的id
 @discussion 用于分页功能
 @result 数据源最后一条数据的id
 */
- (long long)catchTheLastDataSourceId
{    
    return [[[_dataSource objectAtIndex:(_dataSource.count - 1)] objectForKey:@"id"] longLongValue];
}

/*!
 @abstract 用于测试一个订单的提醒按钮是否该显示
 @discussion 用于cellForRow方法
 @result bool显示还是不显示
 */
- (BOOL)buttonShowTesting:(NSDictionary *)order
{
    BOOL result = false;
    for (NSNumber* oid in _remindButtonHiddenRecords) {
        
        if ([oid integerValue] == [order[@"id"] integerValue]) {
            
            result = true;
            break;
        }
    }
    
    return result;
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //下拉刷新
    if (refreshView == _header) {
        
        [self refreshViewByCheckId:nil];
    }
    
    //上拉加载更多
    else {
        
        NSString *checkId = [NSString stringWithFormat:@"%lld", [self catchTheLastDataSourceId]];
        
        //发送加载更多的请求,数据接受成功后，设置_reloading
        [self refreshViewByCheckId:checkId];
    }
}

//刷新tableview
- (void)reloadTableView
{
    [self.tableView reloadData];
    // 结束刷新状态
    [_header endRefreshing];
    [_footer endRefreshing];
}

- (void)dealloc
{
    _dataSource = nil;
}

@end
